<template>
    <el-row>
        <!-- 左侧区域 -->
        <el-col :span="8" style="padding-right:10px">
            <!-- 左上卡片 -->
            <el-card class="box-card">
                <!-- 左上个人信息 -->
                <div class="user">
                    <img :src="adminInfo.picUrl" alt="">
                    <div class="userinfo">
                        <p class="name" v-text="adminInfo.nickname ? adminInfo.nickname : '默认昵称'" ></p>
                        <p class="access">超级管理员</p>
                    </div>
                </div>
                <!-- 左上登录信息 -->
                <div class="login-info">
                    <p>上次登录时间: <span>{{lastDate}}</span></p>
                    <p>上次登录地点: <span>北京</span></p>
                </div>
            </el-card>
            <!-- 左下卡片 -->
            <!-- <el-card style=" margin-top:20px;  height:475px">
                <div style="font-weight: bold">库存书籍</div>
                <el-table :data="tableData"  style="width: 100%">
                    <el-table-column  v-for="(val,key) in tableLabel"  :prop="key"  :label="val" :key="key"  show-overflow-tooltip/>
                </el-table>
            </el-card> -->
            <el-card style=" margin-top:20px;  height:475px">
                <div style="font-weight: bold">库存书籍</div>
                <el-table :data="wxTableData"  style="width: 100%">
                    <!-- key 是索引，val是实值 -->
                    <!-- <el-table-column  v-for="(val,key) in tableLabel"  :prop="key"  :label="val" :key="key"  show-overflow-tooltip/> -->
                    <el-table-column prop="name" label="书籍名称" show-overflow-tooltip/>
                    <el-table-column prop="spot" label="校区" show-overflow-tooltip/>
                    <el-table-column prop="author" label="作者" show-overflow-tooltip/>
                    <el-table-column prop="number" label="数量" show-overflow-tooltip/>
                </el-table>
            </el-card>
        </el-col>

        <!-- 右侧区域 -->
        <el-col :span="16" style="padding-left:10px">
            <div class="num">
                <!-- 右上卡片 -->
                <el-card v-for="item in wxCountData" :key="item.name" :body-style="{display: 'flex' ,padding:0}">
                    <i class="icon" :class="`el-icon-${item.icon}`" :style="{background:item.color}"></i>
                    <div class="detail">
                        <p class="price">{{ item.value }}本</p>
                        <p class="desc">{{ item.name }}</p>
                    </div>
                </el-card>
            </div>
            <!-- 右下卡片 -->
            <el-card style="height: 280px">
                <!-- 折线图 -->
                <div style="font-weight: bold">最近收到书籍</div>
                <div ref="echarts1" style="height: 280px"></div>
            </el-card>
            <div class="graph">
                    <!-- 柱状图 -->
                    <el-card style="height: 280px">
                        <div style="font-weight: bold">用户统计</div>
                        <div ref="echarts2" style="height: 260px;"></div>
                    </el-card>
                    <!-- 饼状图 -->
                    <el-card style="height: 280px">
                        <div style="font-weight: bold">书籍所属学院</div>
                        <div ref="echarts3" style="height: 240px;"></div>
                    </el-card>
            </div>
        </el-col>
    </el-row>
</template>

<script>
import { getData } from '../api'
import { getAdminInfo } from '../api'
import * as echarts from 'echarts'
export default{
    name:'Home',
    data(){
        return {
            adminInfo:'',
            db:'',
            lastDate:'',//上次登录时间
            // tableData:[],
            wxTableData:[],
            // tableLabel:{
            //     name:'书籍名称',
            //     // number:'书籍数量',
            //     todayBuy:'今日领取',
            //     monthBuy: '本月领取',
            //     totalBuy:'总领取'
            // },
            wxCountData:[
                {
                    name:"本部本月收到书籍",
                    value:0,
                    icon:"remove",
                    color:"#2ec7c9"
                },
                {
                    name:"沙河本月收到书籍",
                    value:0,
                    icon:"sort",
                    color:"#ffb980"
                },
                {
                    name:"本月收到书籍",
                    value:0,
                    icon:"circle-plus",
                    color:"#5ab1ef"
                },
                {
                    name:"本部书籍余量",
                    value:0,
                    icon:"remove",
                    color:"#2ec7c9"
                },
                {
                    name:"沙河书籍余量",
                    value:0,
                    icon:"sort",
                    color:"#ffb980"
                },
                {
                    name:"今日收到书籍",
                    value:0,
                    icon:"circle-plus",
                    color:"#5ab1ef"
                },
            ],
            //饼图
            wxVideoData:[],
            //折线图
            wxOrderData:{
                date:['2023-01','2023-02','2023-03','2023-04','2023-05'],
                data:[]
            },
            //柱状图
            wxUserData:[
                {
                date:'2023-01-01',
                new:0,
                total:0
            },                
            {
                date:'2023-01-01',
                new:0,
                total:0
            },
            {
                date:'2023-01-01',
                new:0,
                total:0
            },
            {
                date:'2023-01-01',
                new:0,
                total:0
            } 
        ],
            // countData:[//未废用
            //     {
            //         name:"本部今日收到书籍",
            //         value:21,
            //         icon:"remove",
            //         color:"#2ec7c9"
            //     },
            //     {
            //         name:"沙河今日收到书籍",
            //         value:53,
            //         icon:"sort",
            //         color:"#ffb980"
            //     },
            //     {
            //         name:"今日收到书籍",
            //         value:32,
            //         icon:"circle-plus",
            //         color:"#5ab1ef"
            //     },
            //     {
            //         name:"本部书籍余量",
            //         value:865,
            //         icon:"remove",
            //         color:"#2ec7c9"
            //     },
            //     {
            //         name:"沙河书籍余量",
            //         value:1898,
            //         icon:"sort",
            //         color:"#ffb980"
            //     },
            //     {
            //         name:"本月收到书籍",
            //         value:1033,
            //         icon:"circle-plus",
            //         color:"#5ab1ef"
            //     },
            // ]
        }
    },
    methods:{
        initdb(){
            let that = this
            var c1 = new that.$cloud.Cloud({
                 //必填，表示是未登录模式
                identityless: true,
                //资源方 AppID
                resourceAppid: 'wx3a07f3c2fa333336',
                //资源方环境 ID
                resourceEnv: 'ayaka557-2gh3t7jm380b9701',
            })
            c1.init()
            // console.log('c1',c1);
            //获取云数据库信息
            this.db = c1.database();
            // console.log('db',this.db)
        },
        getLastDate(){
            let dt = new Date()
            let year = dt.getFullYear();
            let month = (dt.getMonth() + 1).toString().padStart(2, '0');
            let day = dt.getDate().toString().padStart(2, '0');
            this.lastDate = `${year}-${month}-${day}`;
        },
        getWxCountData(){//获取较为复杂，单独一个函数
            // 沙河本月获取书籍
            // 获取当前日期
            const now = new Date();
            // 获取当前月份的第一天
            const startDate = new Date(now.getFullYear(), now.getMonth(), 1);
            startDate.setHours(0, 0, 0, 0);
            // 获取下一个月份的第一天
            // const endDate = new Date(now.getFullYear(), now.getMonth() + 1, 1);
            const endDate = now.getMonth() === 11 ? new Date(now.getFullYear() +1, 0, 1):new Date(now.getFullYear(), now.getMonth() + 1, 1)
            endDate.setHours(0, 0, 0, 0);
            // 将时间设置为当前月份最后一天的23:59:59.999
            endDate.setMilliseconds(-1);

            //本部本月收到书籍
            this.db.collection('to_goods')
            .where({
                // 假设注册时间字段为 'registerDate'
                post_date: this.db.command.gte(startDate).and(this.db.command.lte(endDate)),
                spot:'本部校区'
            })
            .count()
            .then(res => {
                console.log('本部这个月获取的书籍',res);
                //修改第一个内容
                this.wxCountData[0].value = res.total
            })
            .catch(err => {
                console.log(err);
            });

            //沙河本月收到书籍
            this.db.collection('to_goods')
            .where({
                // 假设注册时间字段为 'registerDate'
                post_date: this.db.command.gte(startDate).and(this.db.command.lte(endDate)),
                spot:'沙河校区'
            })
            .count()
            .then(res => {
                console.log('沙河这个月获取的书籍',res);
                //修改第一个内容
                this.wxCountData[1].value = res.total
            })
            .catch(err => {
                console.log(err);
            });

            //本月收到书籍，防止异步问题，获取而不是相加
            this.db.collection('to_goods')
            .where({
                // 假设注册时间字段为 'registerDate'
                post_date: this.db.command.gte(startDate).and(this.db.command.lte(endDate))
            })
            .count()
            .then(res => {
                console.log('总共这个月获取的书籍',res);
                //修改第一个内容
                this.wxCountData[2].value = res.total
            })
            .catch(err => {
                console.log(err);
            });

            //书籍总量
            const $ = this.db.command.aggregate
            this.db.collection('goods').aggregate()
            .group({
                //根据college字段分组
                _id:'$spot',
                //计算里面的个数，这样的话就是书籍（每个类别算一个）所属学院
                // count: $.sum(1)
                //下面这个就是书籍（数量）所属学院
                totalNum: $.sum('$number')
            })
            .end()
            .then(res => {
                console.log('总量书籍',res);
                //如果是先本部再沙河
                if(res.list[0]._id = '本部校区'){
                    this.wxCountData[3].value = res.list[0].totalNum
                    this.wxCountData[4].value = res.list[1].totalNum
                }else{
                    this.wxCountData[3].value = res.list[1].totalNum
                    this.wxCountData[4].value = res.list[4].totalNum
                }
            })
            .catch(err => {
                console.log(err);
            });

            //今日获取书籍
            // 获取今天的日期
            const startDateToday = new Date();
            startDateToday.setHours(0, 0, 0, 0);

            const endDateToday = new Date();
            endDateToday.setHours(23, 59, 59, 999);

            // 查询数据库获取今天的书籍
            this.db.collection('to_goods')
            .where({
                post_date: this.db.command.gte(startDateToday).and(this.db.command.lte(endDateToday))
            })
            .count()
            .then(res => {
                console.log('今天收到的书籍', res);
                this.wxCountData[5].value = res.total
            })
            .catch(err => {
                console.log(err);
            });
        },
        //封装一下wxUserData获取,改为异步函数
        async getWxUserData(){
            let now = new Date();
            // 获取当前月份的第一天
            let startDate = new Date(now.getFullYear(), now.getMonth(), 1);
            startDate.setHours(0, 0, 0, 0);

            // 获取下一个月份的第一天,如果是12月则变成明年1月
            let endDate = now.getMonth() === 11 ? new Date(now.getFullYear() +1, 0, 1):new Date(now.getFullYear(), now.getMonth() + 1, 1)
            endDate.setHours(0, 0, 0, 0);

            // 将时间设置为当前月份最后一天的23:59:59.999
            endDate.setMilliseconds(-1);

            let i = 0
            //一共查找四个月
            for (i = 0; i < 4; i++) {
                //保证月份不会溢出
                startDate = now.getMonth()-i < 0? new Date(now.getFullYear() - 1, now.getMonth()-i + 12, 1) : new Date(now.getFullYear(), now.getMonth()-i, 1)
                endDate =now.getMonth() + 1 -i < 0 ? new Date(now.getFullYear() -1, now.getMonth()-i + 13, 1): new Date(now.getFullYear(), now.getMonth() + 1 -i, 1)
                let year = startDate.getFullYear();
                let month = (startDate.getMonth() + 1).toString().padStart(2, '0');
                this.wxUserData[i].date = `${year}-${month}`

                try {
                    const totalRes = await this.db.collection('users')
                        .where({
                            // 小于最晚时间，这个月结束之前创建用户
                            registration_time: this.db.command.lte(endDate)
                        })
                        .count();
                    
                    this.wxUserData[i].total = totalRes.total;

                    const newRes = await this.db.collection('users')
                        .where({
                            // 这个月创建的用户
                            registration_time: this.db.command.gte(startDate).and(this.db.command.lte(endDate))
                        })
                        .count();
                    
                    this.wxUserData[i].new = newRes.total;
                    // console.log('userData', this.wxUserData);


                    } catch (err) {
                    console.log(err);
                    }
                }

                this.wxUserData.reverse()
        },
        //折线图
        async getWxOrderData(){
            let now = new Date();
            // 获取当前月份的第一天
            let startDate = new Date(now.getFullYear(), now.getMonth(), 1);
            startDate.setHours(0, 0, 0, 0);

            // 获取下一个月份的第一天,如果是12月则变成明年1月
            let endDate = now.getMonth() === 11 ? new Date(now.getFullYear() +1, 0, 1):new Date(now.getFullYear(), now.getMonth() + 1, 1)
            endDate.setHours(0, 0, 0, 0);

            // 将时间设置为当前月份最后一天的23:59:59.999
            endDate.setMilliseconds(-1);

            let i = 0
            //一共查找五个月
            for (i = 0; i < 5; i++) {
                //保证月份不会溢出
                startDate = now.getMonth()-i < 0? new Date(now.getFullYear() - 1, now.getMonth()-i + 12, 1) : new Date(now.getFullYear(), now.getMonth()-i, 1)
                endDate =now.getMonth() + 1 -i < 0 ? new Date(now.getFullYear() -1, now.getMonth()-i + 13, 1): new Date(now.getFullYear(), now.getMonth() + 1 -i, 1)
                let year = startDate.getFullYear();
                let month = (startDate.getMonth() + 1).toString().padStart(2, '0');
                this.wxOrderData.date[i] = `${year}-${month}`
                    //创建一个tempData放入数组
                var tempData = {
                    '本部校区':0,
                    '沙河校区':0
                }
                try {
                    //沙河本月收到书籍
                    const shaHeRes = await this.db.collection('to_goods')
                        .where({
                            // 假设注册时间字段为 'registerDate'
                            post_date: this.db.command.gte(startDate).and(this.db.command.lte(endDate)),
                            spot:'沙河校区'
                        })
                        .count()

                    tempData.沙河校区 = shaHeRes.total;

                    const benBuRes = await this.db.collection('to_goods')
                        .where({
                            // 假设注册时间字段为 'registerDate'
                            post_date: this.db.command.gte(startDate).and(this.db.command.lte(endDate)),
                            spot:'本部校区'
                        })
                        .count()

                    tempData.本部校区 = benBuRes.total;


                    //加入数组
                    this.wxOrderData.data.push(tempData)
                    } catch (err) {
                    console.log(err);
                    }
                }

                 this.wxOrderData.date.reverse()
                 this.wxOrderData.data.reverse()
                 console.log('wxOrderData',this.wxOrderData);
                 
        },
        async getWxData(){
            //右上countData
            this.getWxCountData()

            //左下表格TableData
            this.db.collection('goods')
                .orderBy('number','desc')
                .get()
                .then(res => {
                    console.log('wxTableData',res.data);
                    this.wxTableData = res.data
                })
                .catch(err => {
                    console.log(err);
                });

            

                        
            //饼状图
            const echarts3= echarts.init(this.$refs.echarts3)
            //饼图
            const $ = this.db.command.aggregate
            this.db.collection('goods').aggregate()
            .group({
                //根据college字段分组
                _id:'$college',
                //计算里面的个数，这样的话就是书籍（每个类别算一个）所属学院
                // count: $.sum(1)
                //下面这个就是书籍（数量）所属学院
                totalNum: $.sum('$number')
            })
            .sort({ totalNum: -1 }) // 按书籍数量降序排序
            .limit(5)//只要前5个
            .end()
            .then(res => {
                this.wxVideoData = res.list
                console.log('饼图',this.wxVideoData)
                const formatWxVideoData = this.wxVideoData.map(item => ({
                    name: item._id,  // 将 `_id` 映射为 `name`
                    value: item.totalNum // 将 `totalNum` 映射为 `value`
                }));
                const echarts3Option ={
                tooltip:{
                    trigger:"item",
                },
                color:[//增加饼图的颜色
                    "#0f78f4",
                    "#dd536b",
                    "#9462e5",
                    // "#a6a6a6",
                    "#e1bb22",
                    "#39c362",
                    // "#3ed1cf",
                ],
                series:[
                        {
                        data:formatWxVideoData,
                        type:'pie'
                        }
                    ]
                }
                echarts3.setOption(echarts3Option)
            })
            .catch(err => {
                console.log(err);
            });
           

            //柱状图
            //封装一下wxUserData获取，需要等待userData获取完后再画图
            await this.getWxUserData()
            
            const echarts2= echarts.init(this.$refs.echarts2)
            const echarts2Option={
                legend:{
                    //图例文字颜色
                    textStyle:{
                        color: "#333",
                    },
                },
                grid:{
                    left:"20%",
                },
                //提示框
                tooltip:{
                    trigger:"axis",
                },
                xAxis:{
                    type:"category",//类目轴
                    data: this.wxUserData.map(item =>item.date),
                    axisLine:{
                        lineStyle:{
                            color:"#17b3a3",
                        },
                    },
                    axisLable:{
                        interval:0,
                        color:"#333",
                    },
                },
                yAxis:[
                    {
                        type:"value",
                        axisLine:{
                            lineStyle:{
                                color:"#17b3a3",
                            },
                        },
                    },
                ],
                color:["#2ec7c9","#b6a2de"],
                series:[
                    {
                        name:'新增用户',
                        data:this.wxUserData.map(item =>item.new),
                        type:'bar'
                    },
                    {
                        name:'总用户',
                        data:this.wxUserData.map(item =>item.total),
                        type:'bar'
                    }
                ]
            }
            echarts2.setOption(echarts2Option)

            //折线图
            await this.getWxOrderData()

            const echarts1 = echarts.init(this.$refs.echarts1)
            var echarts1Option={}
            //获取xAxis数据                
            const xAxis = Object.keys(this.wxOrderData.data[0])
                // console.log(xAxis)
            const xAxisData = {
                data:xAxis
            }
            //***self***
            const dateData = {
                data:this.wxOrderData.date
            }
            //***self***

            // echarts1Option.xAxis = xAxisData
            echarts1Option.xAxis = dateData
            echarts1Option.yAxis = {}
            echarts1Option.legend = xAxisData
            echarts1Option.series = []
            xAxis.forEach(key =>{
                echarts1Option.series.push({
                    name: key,
                    data: this.wxOrderData.data.map(item => item[key]),
                    type:'line'
                })
            })
            console.log('lineGraphData',echarts1Option.series);
            
            // console.log(echarts1Option)
            //显示图表
            echarts1.setOption(echarts1Option)
            
        }
    },
    //mock已经废用了这项数据，没有完全费用
    mounted(){
        this.initdb()
        this.getLastDate()

        //获取admin信息，有后端代码
        getAdminInfo().then(ret =>{
            this.adminInfo = ret.data.data
            console.log('admininfo',this.adminInfo)
            console.log('adminInfoNickname',this.adminInfo.nickname)
        })

        this.getWxData()



        //动态传递左下表格数据
        getData().then(({data})=>{//解构赋值到函数参数
            // console.log(data)
        //     const {tableData} = data.data
        //     // console.log(tableData)
        // //表格
        //     this.tableData = tableData//动态数据替换

        //折线图
            //基于准备好的dom，初始化echarts实例
            // const echarts1 = echarts.init(this.$refs.echarts1)
            // var echarts1Option={}
            // //获取xAxis数据                
            // const {orderData} = data.data
            // const xAxis = Object.keys(orderData.data[0])
            //     // console.log(xAxis)
            // const xAxisData = {
            //     data:xAxis
            // }
            // //***self***
            // const dateData = {
            //     data:orderData.date
            // }
            // //***self***

            // // echarts1Option.xAxis = xAxisData
            // echarts1Option.xAxis = dateData
            // echarts1Option.yAxis = {}
            // echarts1Option.legend = xAxisData
            // echarts1Option.series = []
            // console.log('orderData',orderData);
            // xAxis.forEach(key =>{
            //     echarts1Option.series.push({
            //         name: key,
            //         data: orderData.data.map(item => item[key]),
            //         type:'line'
            //     })
            // })
            // console.log('lineGraphData',echarts1Option.series);
            
            // // console.log(echarts1Option)
            // //显示图表
            // echarts1.setOption(echarts1Option)

        //柱状图
            // const echarts2= echarts.init(this.$refs.echarts2)
            // const {userData} = data.data
            // const echarts2Option={
            //     legend:{
            //         //图例文字颜色
            //         textStyle:{
            //             color: "#333",
            //         },
            //     },
            //     grid:{
            //         left:"20%",
            //     },
            //     //提示框
            //     tooltip:{
            //         trigger:"axis",
            //     },
            //     xAxis:{
            //         type:"category",//类目轴
            //         data: userData.map(item =>item.date),
            //         axisLine:{
            //             lineStyle:{
            //                 color:"#17b3a3",
            //             },
            //         },
            //         axisLable:{
            //             interval:0,
            //             color:"#333",
            //         },
            //     },
            //     yAxis:[
            //         {
            //             type:"value",
            //             axisLine:{
            //                 lineStyle:{
            //                     color:"#17b3a3",
            //                 },
            //             },
            //         },
            //     ],
            //     color:["#2ec7c9","#b6a2de"],
            //     series:[
            //         {
            //             name:'新增用户',
            //             data:userData.map(item =>item.new),
            //             type:'bar'
            //         },
            //         {
            //             name:'活跃用户',
            //             data:userData.map(item =>item.active),
            //             type:'bar'
            //         }
            //     ]
            // }
            // echarts2.setOption(echarts2Option)
        
        //饼状图
            // const echarts3= echarts.init(this.$refs.echarts3)
            // const {videoData} = data.data
            // const echarts3Option ={
            //     tooltip:{
            //         trigger:"item",
            //     },
            //     color:[//增加饼图的颜色
            //         "#0f78f4",
            //         "#dd536b",
            //         "#9462e5",
            //         "#a6a6a6",
            //         "#e1bb22",
            //         "#39c362",
            //         "#3ed1cf",
            //     ],
            //     series:[
            //         {
            //             data:videoData,
            //             type:'pie'
            //         }
            //     ]
            // }
            // echarts3.setOption(echarts3Option)

        })
    }
}
</script>

<style lang="less" scoped>
.user{
    padding-bottom: 20px;
    margin-bottom: 20px;
    border-bottom: 1px solid #ccc ;
    display: flex;
    align-items: center;
    img{
        margin-right: 40px;
        width: 150px;
        height: 150px;
        border-radius: 50%;
    }
    .userinfo{
        .name{
            font-size: 32px;
            margin-bottom: 10px;
        }
        .access{
            color: #999999;
        }
    }
}

.login-info{
    p{
        line-height: 28px;
        font-size: 14px;
        color:#999999;
        span{
            color:#666666;
            margin-left: 60px;
        }
    }
}
.num{
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    .icon{
        width: 80px;
        height: 80px;
        font-size: 30px;
        text-align: center;
        line-height: 80px;
        color: #fff;
    }
    .detail{
        margin-left: 15px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        .price{
            font-size: 30px;
            margin-bottom: 10px;
            line-height: 30px;
            height: 30px;
        }
        .desc{
            font-size: 14px;
            color: #999;
            text-align: center;
        }
    }
    .el-card{
        width: 32%;
        margin-bottom: 20px;
    }
}
.graph{
    margin-top: 20px;
    display: flex;
    justify-content: space-between;
    .el-card{
        width: 48%;
    }
}
</style>